#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*-  
from google.appengine.ext import db
from milonpy import NMinet
class ipv4      (db.Model):
    rir=    db.StringProperty   (indexed=False,  required=True,  verbose_name="First 2 chars of RIR"  )
    cc=     db.StringProperty   (indexed=False,  required=True,  verbose_name="iso 2 char country code")
    ips=    db.IntegerProperty  (indexed=True,   required=True,  verbose_name="Block's start IP as Integer")
    ipe=    db.IntegerProperty  (indexed=False,  required=True,  verbose_name="Block's end IP as Integer")
    dt=     db.StringProperty   (indexed=False,  required=True,  verbose_name="date as plain Text i.e:20101004") 
    bt=     db.IntegerProperty  (indexed=False,  required=True,  verbose_name="block type 2 = assigned 4 = allocated")
    @classmethod 
    def autoKeyName(cls, ipstart):
        return NMinet.IPNumToQuad(ipstart)
    @classmethod
    def setItemFromRir(cls, rirRecord, put=True):  # a rir record format=      'ripencc|RS|ipv4|46.16.104.0|2048|20101004|allocated\n',
        rcd=rirRecord.split('|')
        if rcd[2] !='ipv4':return False
        ipStart= NMinet.IPencode(rcd[3]) 
        ipEnd=ipStart+ int(rcd[4])
        bt= 2 if rcd[6].startswith('as') else 4
        kn = cls.autoKeyName(ipStart) 
        item=cls(key_name=kn,  rir=rcd[0][0:2],  cc=rcd[1].lower() , ips=ipStart, ipe=ipEnd, dt=rcd[5],  bt=bt) 
        if put: return item.put()
        else:return item       
    @classmethod
    def getItemFromIpInt(cls, ipInt): 
        query = cls.all().filter('ips <=', ipInt).order("-ips") 
        results = query.fetch(1, rpc= db.create_rpc(read_policy=db.EVENTUAL_CONSISTENCY ) )
        if len(results) == 1:
            ipv4=results[0]
            if ipv4.ipe  >= ipInt:return ipv4
        return None    

    
    







#from google.appengine.ext import deferred  
# 
# 
#class AuthToken(db.Model):
#    """Auth Token. 
#    A temporary auth token that we will use to authenticate a user with a
#    third party website. (We need to store the data while the user visits
#    the third party website to authenticate themselves.) 
#    TODO: Implement a cron to clean out old tokens periodically.
#    """ 
#    service   = db.StringProperty(required=True)
#    token     = db.StringProperty(required=True)
#    secret    = db.StringProperty(required=True)
#    created   = db.DateTimeProperty(auto_now_add=True)
#
#
#                      
#class ApplService(NMdb.nmModel):
#    application_code         = db.StringProperty(required=True, indexed=False,verbose_name='Unique Application Code Name')
#    application_title        = db.StringProperty(required=False, indexed=False,verbose_name='Application Name')
#    application_description  = db.TextProperty(required=False)
#    service_provider         = db.StringProperty(required=True, indexed=False)  
#    consumer_key             = db.StringProperty(required=False, indexed=False)
#    consumer_secret          = db.StringProperty(required=False, indexed=False)
#    url_request              = db.LinkProperty(required = False,indexed=False)
#    url_access               = db.LinkProperty(required = False,indexed=False)        
#    url_authorize            = db.LinkProperty(required = False, indexed=False) 
#        
#    def put(self, **kwargs ):
#        self._key_name=self.service_provider+"|"+self.application_code
#        return super(ApplService, self).put(**kwargs) 
        
#class ApplUser  (NMdb.nmModel):
#    """TODO set key to appkey + userID then query by key"""
#    appkey=     db.ReferenceProperty   (ApplService, required=True)  
#    apSpcD=     NMdb.DicPropertyEval   (indexed=False, required=False)
#    user=       db.UserProperty        (indexed=False, auto_current_user_add=True) 
#    userID=     db.StringProperty      (required=False,indexed=True, verbose_name='user ID Coz Email can change')
#    tokn=       db.StringProperty      (required=True, indexed=False,verbose_name='user token')
#    secr=       db.StringProperty      (required=True, indexed=False,verbose_name='user secret') 
#    accTP=      db.StringProperty      (required=False,indexed=False,verbose_name='acount Type i.e. twitter, gmail etc')


            
     
    
    
